package coms.mianshi.proxy.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: item_02
 * @description: 静态代理
 * @author: LL
 * @create: 2021-03-02 13:57
 */
//代理对象UserDapProxy
public class UserDapProxy implements MethodInterceptor {

    private Object target;//维护一个目标对象

    public UserDapProxy(final Object target) {
        this.target = target;
    }

    //为目标对象生成代理对象
    public Object getProxyInstance() {
        //工具类
        final Enhancer en = new Enhancer();
        //设置父类
        en.setSuperclass(this.target.getClass());
        //设置回调函数
        en.setCallback(this);
        return en.create();
    }

    public static void main(final String[] args) {
        //目标对象
        final UserDao target = new UserDao();
        System.out.println(target.getClass());
        //代理对象
        final UserDao proxy = (UserDao) new UserDapProxy(target).getProxyInstance();
        System.out.println(proxy.getClass());
        //执行代理对象方法
        proxy.save();
    }


    @Override
    public Object intercept(final Object obj, final Method method, final Object[] objects, final MethodProxy methodProxy) throws Throwable {
        System.out.println("开启事务");
        //执行目标对象方法
        final Object returnValue = method.invoke(this.target, objects);
        System.out.println("关闭事务");
        return null;
    }
}
